﻿package com.androider.timememory.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import com.androider.timememory.R;
import com.androider.timememory.adapter.DiffAdapter;
import com.androider.timememory.adapter.RecordAdapter;
import com.androider.timememory.db.Record;
import com.androider.timememory.db.RecordModel;
import com.androider.timememory.service.SMSService;
import com.androider.timememory.utils.ActivityUtil;
import com.androider.timememory.utils.Constants;
import com.androider.timememory.utils.FileUtil;
import com.androider.timememory.utils.ImageUtil;
import com.androider.timememory.utils.RecordUtil;
import com.androider.timememory.utils.StringUtil;
import com.androider.timememory.view.CardImageView;
import com.androider.timememory.view.Panel;
import com.androider.timememory.view.ScrollLayout;
import com.androider.timememory.view.ScrollLayout.OnSnapToEndListener;
import com.androider.timememory.view.TitleFlowIndicator;
import com.androider.timememory.view.ViewFlow;
import com.androider.timememory.view.ViewFlow.ViewSwitchListener;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RadioGroup.LayoutParams;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;


public class TimeMemory extends Activity {
	
	private final static int REQUEST_CODE_TAKE_PHOTO = 1;
	private final static int REQUEST_CODE_TAKE_VIDEO = 2;
	private final static int REQUEST_CODE_TAKE_RECORD = 3;
	
	private final static int HANDLER_LISTVIEW = 1;
	
	private Random random = new Random(100);
	
	private Resources resources;
	private Context mContext;
	private UpdateUIReceiver receiver;
	
	private ViewFlow viewFlow;
	private TitleFlowIndicator indicator;
	private DiffAdapter adapter;
	private Button search;
	/********* menu *********/
	public PopupWindow menuWindow;
	private LinearLayout menuSendsms;
	private LinearLayout menuWhitelist;
	private LinearLayout menuGuide;
	private LinearLayout menuAbout;
	/********* guide ********/
	private ScrollLayout scrollLayout;
	private LinearLayout guideBg;
	private ImageView img1;
	private ImageView img2;
	private ImageView img3;
	private ImageView img4;
    
    /******* new note ********/
    private GridView newrecordGridView;
    private Panel panel;
    private LinearLayout newNoteLayout;
    private LinearLayout upBgLayout;
    private LinearLayout downBgLayout;
    private TextView titleDate;
    private EditText newnoteEditText;
    private Button negative;
    private Button positive;
    private CheckBox categoryFamily;
    private CheckBox categoryLover;
    private CheckBox categoryFriend;
    
    /***** lists *****/
    private ListView familyList;
    private ListView loverList;
    private ListView friendList;
    
    private TextView familyNoData;
    private TextView loverNoData;
    private TextView friendNoData;
    
    private RecordAdapter mFamilyAdapter;
    private RecordAdapter mLoverAdapter;
    private RecordAdapter mFriendAdapter;
    private ArrayList<HashMap<String, Object>> mFamilyData;
    private ArrayList<HashMap<String, Object>> mLoverData;
    private ArrayList<HashMap<String, Object>> mFriendData;
    
    private boolean isShow = false;
    private boolean isEditingNote = false;
    private long time;
    private int mCurrentPage = 1;
    
    private SharedPreferences prefs;
    
    /******* welcome screen ********/
    private LinearLayout welcomeLayout1;
    private LinearLayout welcomeLayout2;
    private LinearLayout welcomeLayout3;
    private ScrollView welcomScroll;
    private CardImageView cardFaimly = null;
    private CardImageView cardLover = null;
    private CardImageView cardFriend = null;
    private CardImageView cardLatest = null;
    private Bitmap cardBitmapFaimly = null;
    private Bitmap cardBitmapLover = null;
    private Bitmap cardBitmapFriend = null;
    private Bitmap cardBitmapLatest = null;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        mContext = TimeMemory.this;
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        resources = mContext.getResources();
        
        init();
        
        receiver = new UpdateUIReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constants.ACTION_RECORD_ADD);
        registerReceiver(receiver, filter);
        
        ActivityUtil.startService(mContext, SMSService.class);
        
        //是否需要显示教程
        boolean guide = prefs.getBoolean("guide", true);
		if(!guide) {
			scrollLayout.setVisibility(View.GONE);
			guideBg.setVisibility(View.GONE);
		} else { //加载教程图片
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
					WindowManager.LayoutParams.FLAG_FULLSCREEN);
			img1 = new ImageView(this);
			img1.setImageResource(R.drawable.guide_1);
			img2 = new ImageView(this);
			img2.setImageResource(R.drawable.guide_2);
			img3 = new ImageView(this);
			img3.setImageResource(R.drawable.guide_3);
			img4 = new ImageView(this);
			img4.setImageResource(R.drawable.guide_4);
			scrollLayout.addView(img1);
			scrollLayout.addView(img2);
			scrollLayout.addView(img3);
			scrollLayout.addView(img4);
			
			SharedPreferences.Editor editor = prefs.edit();
			editor.putBoolean("guide", false);
			editor.commit();
		}
        
    }
	
	@Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        ActivityUtil.stopService(mContext, SMSService.class);
        img1 = null;
        img2 = null;
        img3 = null;
        img4 = null;
        cardFaimly = null;
        cardLover = null;
        cardFriend = null;
        cardLatest = null;
        
        if(cardBitmapFaimly != null){
        	cardBitmapFaimly.recycle();
        }
        if(cardBitmapLover != null){
        	cardBitmapLover.recycle();
        }
        if(cardBitmapFriend != null){
        	cardBitmapFriend.recycle();
        }
        if(cardBitmapLatest != null){
        	cardBitmapLatest.recycle();
        }
        
        super.onDestroy();
    }
	
    private void init() {
		setViews();
		setMenu();
		initLists();
		setOnListeners();
		initGridView();
		initWelcomeScreen();
	}
    
    /**
	 * Set up views.
	 */
	private void setViews() {
		viewFlow = (ViewFlow) findViewById(R.id.viewflow);
		indicator = (TitleFlowIndicator) findViewById(R.id.viewflowindic);
		adapter = new DiffAdapter(mContext);
        viewFlow.setAdapter(adapter, 1);
		indicator.setTitleProvider(adapter);
		viewFlow.setFlowIndicator(indicator);
		search = (Button) findViewById(R.id.search);
		
		scrollLayout = (ScrollLayout) findViewById(R.id.guide_scrolllayout);
		guideBg = (LinearLayout) findViewById(R.id.guide_bg);
		
        newrecordGridView = (GridView) findViewById(R.id.panelContent);
        panel = (Panel) findViewById(R.id.newrecordPanel);
        
        newNoteLayout = (LinearLayout) findViewById(R.id.newnote_layout);
        upBgLayout = (LinearLayout) findViewById(R.id.new_record_bg_up);
        downBgLayout = (LinearLayout) findViewById(R.id.new_record_bg_down);
        titleDate = (TextView) findViewById(R.id.title_date);
        titleDate.setText(StringUtil.getCurrnetDate("yyyy年MM月dd日"));
        newnoteEditText = (EditText) findViewById(R.id.new_note_edittext);
        negative = (Button) findViewById(R.id.negative);
        positive = (Button) findViewById(R.id.positive);
        categoryFamily = (CheckBox) findViewById(R.id.category_family);
        categoryLover = (CheckBox) findViewById(R.id.category_lover);
        categoryFriend = (CheckBox) findViewById(R.id.category_friend);
        
        familyList = (ListView) findViewById(R.id.family_list);
        loverList = (ListView) findViewById(R.id.lover_list);
        friendList = (ListView) findViewById(R.id.friend_list);
        
        familyNoData = (TextView) findViewById(R.id.list_family_no_data);
        loverNoData = (TextView) findViewById(R.id.list_lover_no_data);
        friendNoData = (TextView) findViewById(R.id.list_friend_no_data);
        
        //welcome screen
        welcomeLayout1 = (LinearLayout) findViewById(R.id.welcome_Layout_1);
        welcomeLayout2 = (LinearLayout) findViewById(R.id.welcome_Layout_2);
        welcomeLayout3 = (LinearLayout) findViewById(R.id.welcome_Layout_3);
        welcomScroll = (ScrollView) findViewById(R.id.welcome_scroll);
        
    }
	
	private void setMenu() {
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
		View layout = inflater.inflate(R.layout.menu_layout, null);
		
		menuSendsms = (LinearLayout)layout.findViewById(R.id.menu_sendsms);
		menuWhitelist = (LinearLayout)layout.findViewById(R.id.menu_whitelist);
		menuGuide = (LinearLayout)layout.findViewById(R.id.menu_guide);
		menuAbout = (LinearLayout)layout.findViewById(R.id.menu_about);
	
		menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); //后两个参数是width和height
		menuWindow.setAnimationStyle(R.style.menuPopupAnimation);
		
		menuSendsms.setOnClickListener(menuSendsmsListener);
		menuWhitelist.setOnClickListener(menuWhitelistListener);
		menuGuide.setOnClickListener(menuGuideListener);
		menuAbout.setOnClickListener(menuAboutListener);
	}
	
	private OnClickListener menuSendsmsListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			startActivity(new Intent(mContext, SendSMS.class));
			menuWindow.dismiss();
		}
	};
	
	private OnClickListener menuWhitelistListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			startActivity(new Intent(mContext, WhiteList.class));
			menuWindow.dismiss();
		}
	};
	
	private OnClickListener menuGuideListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			startActivity(new Intent(mContext, Guide.class));
			menuWindow.dismiss();
		}
	};
	
	private OnClickListener menuAboutListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			startActivity(new Intent(mContext, About.class));
			menuWindow.dismiss();
		}
	};
	
    /**
     * initialize welcome screen
     */
    private void initWelcomeScreen(){
    	addCards();
    	updateDataToCards();
    }
    
    private void addCards(){
		cardFaimly = new CardImageView(this);
		cardFaimly.setImageResource(R.drawable.welcome_card_family);
		cardFaimly.setTitle(R.string.category_family);
		cardFaimly.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, Album.class);
				intent.putExtra(Album.ALBUM_DATA_TYPE, Constants.DATA_TYPE_FAMILY);
				mContext.startActivity(intent);
			}
		});
		welcomeLayout3.addView(cardFaimly, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		cardLover = new CardImageView(this);
		cardLover.setImageResource(R.drawable.welcome_card_lover);
		cardLover.setTitle(R.string.category_lover);
		cardLover.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, Album.class);
				intent.putExtra(Album.ALBUM_DATA_TYPE, Constants.DATA_TYPE_LOVER);
				mContext.startActivity(intent);
			}
		});
		welcomeLayout2.addView(cardLover, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		cardFriend = new CardImageView(this);
		cardFriend.setImageResource(R.drawable.welcome_card_friend);
		cardFriend.setTitle(R.string.category_friend);
		cardFriend.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, Album.class);
				intent.putExtra(Album.ALBUM_DATA_TYPE, Constants.DATA_TYPE_FRIEND);
				mContext.startActivity(intent);
			}
		});
		welcomeLayout2.addView(cardFriend, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
		cardLatest = new CardImageView(this);
		cardLatest.setImageResource(R.drawable.welcome_card_latest);
		cardLatest.setTitle(R.string.category_latest);
		cardLatest.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, Album.class);
				final String[] types = {Constants.DATA_TYPE_FRIEND,
								Constants.DATA_TYPE_LOVER,
								Constants.DATA_TYPE_FAMILY
								};

				random.nextInt();
				intent.putExtra(Album.ALBUM_DATA_TYPE, types[Math.abs(random.nextInt())%3]);
				mContext.startActivity(intent);
			}
		});
		welcomeLayout1.addView(cardLatest, new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		
    }

    private void updateDataToCards(){
    	ArrayList<Integer> usedRecord = new ArrayList<Integer>();
    	
    	final HashMap<String, Object> latestRecord = RecordModel.getLastImageRecord(this);
    	if(latestRecord != null){
    		if(cardBitmapLatest != null){
    			cardBitmapLatest.recycle();
    		}
    		cardBitmapLatest = ImageUtil.BitmapZoomClip(ImageUtil
					.getThumbnail(mContext, (String) latestRecord
							.get("content"), (String) latestRecord
							.get("type")), 480, 220);
    		cardLatest.setImageBitmap(cardBitmapLatest);
    		usedRecord.add((Integer) latestRecord.get("id"));
    		random = new Random(((String)latestRecord.get("note")).length());
    	}

		for (int i = 0; i < mFamilyData.size(); i++) {
			if (mFamilyData.get(i).get("type")
					.equals(RecordUtil.LIST_TYPE_PHOTO)
					|| mFamilyData.get(i).get("type")
							.equals(RecordUtil.LIST_TYPE_VIDEO)) {
				if (usedRecord.contains((Integer) mFamilyData.get(i).get("id"))) {
					continue;
				}
				if(cardBitmapFaimly != null){
					cardBitmapFaimly.recycle();
	    		}
				cardBitmapFaimly = ImageUtil.BitmapZoomClip(ImageUtil
						.getThumbnail(mContext, (String) mFamilyData.get(i)
								.get("content"), (String) mFamilyData.get(i)
								.get("type")), 480, 200);
				cardFaimly.setImageBitmap(cardBitmapFaimly);
				usedRecord.add((Integer) mFamilyData.get(i).get("id"));
				break;
			}
		}

		for (int i = 0; i < mLoverData.size(); i++) {
			if (mLoverData.get(i).get("type")
					.equals(RecordUtil.LIST_TYPE_PHOTO)
					|| mLoverData.get(i).get("type")
							.equals(RecordUtil.LIST_TYPE_VIDEO)) {
				if (usedRecord.contains((Integer) mLoverData.get(i).get("id"))) {
					continue;
				}
				if(cardBitmapLover != null){
					cardBitmapLover.recycle();
	    		}
				cardBitmapLover = ImageUtil.BitmapZoomClip(ImageUtil
						.getThumbnail(mContext,
								(String) mLoverData.get(i).get("content"),
								(String) mLoverData.get(i).get("type")), 230,
						200);
				cardLover.setImageBitmap(cardBitmapLover);
				usedRecord.add((Integer) mLoverData.get(i).get("id"));
				break;
			}
		}

		for (int i = 0; i < mFriendData.size(); i++) {
			if (mFriendData.get(i).get("type")
					.equals(RecordUtil.LIST_TYPE_PHOTO)
					|| mFriendData.get(i).get("type")
							.equals(RecordUtil.LIST_TYPE_VIDEO)) {
				if (usedRecord.contains((Integer) mFriendData.get(i).get("id"))) {
					continue;
				}
				if(cardBitmapFriend != null){
					cardBitmapFriend.recycle();
	    		}
				cardBitmapFriend = ImageUtil.BitmapZoomClip(ImageUtil
						.getThumbnail(mContext, (String) mFriendData.get(i)
								.get("content"), (String) mFriendData.get(i)
								.get("type")), 230, 200);
				cardFriend.setImageBitmap(cardBitmapFriend);
				usedRecord.add((Integer) mFriendData.get(i).get("id"));
				break;
			}
		}
    }
	/**
	 * Initialize lists.
	 */
	private void initLists() {
	    mFamilyData = RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_FAMILY);
	    mFamilyAdapter = new RecordAdapter(mContext, mFamilyData);
	    familyList.setDivider(resources.getDrawable(R.drawable.dot_divider));
	    familyList.setAdapter(mFamilyAdapter);
        
        mLoverData = RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_LOVER);
		mLoverAdapter = new RecordAdapter(mContext, mLoverData);
		loverList.setDivider(resources.getDrawable(R.drawable.dot_divider));
		loverList.setAdapter(mLoverAdapter);
		
		mFriendData = RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_FRIEND);
		mFriendAdapter = new RecordAdapter(mContext, mFriendData);
		friendList.setDivider(resources.getDrawable(R.drawable.dot_divider));
		friendList.setAdapter(mFriendAdapter);
		
		updateListView();
	}
	
	/**
	 * Update the views show in the list, if the data size is zero, the listview will be hidden.
	 */
	private void updateListView() {
		if(mFamilyData != null && mFamilyData.size() > 0) {
	    	familyList.setVisibility(View.VISIBLE);
	    	familyNoData.setVisibility(View.GONE);
	    } else {
	    	familyList.setVisibility(View.GONE);
	    	familyNoData.setVisibility(View.VISIBLE);
	    }
		
		if(mLoverData != null && mLoverData.size() > 0) {
			loverList.setVisibility(View.VISIBLE);
			loverNoData.setVisibility(View.GONE);
		} else {
			loverList.setVisibility(View.GONE);
			loverNoData.setVisibility(View.VISIBLE);
		}
		
		if(mFriendData != null && mFriendData.size() > 0) {
			friendList.setVisibility(View.VISIBLE);
			friendNoData.setVisibility(View.GONE);
		} else {
			friendList.setVisibility(View.GONE);
			friendNoData.setVisibility(View.VISIBLE);
		}
	}
	
	 /**
     * initialize new record panel
     */
    private void initGridView() {
    	ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
    	int [] textIds = {R.string.new_record_note,
    					  R.string.new_record_picture,
    					  R.string.new_record_video,
    					  R.string.new_record_record};
    	int [] imgIds = {R.drawable.new_record_note,
    					 R.drawable.new_record_photo,
    					 R.drawable.new_record_video,
    					 R.drawable.new_record_audio};
    	for(int i = 0; i < 4; i++) {
    		HashMap<String, Object> map = new HashMap<String, Object>();
    		map.put("img", imgIds[i]);
    		map.put("text", this.getResources().getText(textIds[i]).toString());
    		list.add(map);
    	}
    	SimpleAdapter adapter = new SimpleAdapter(this, 
    											  list, 
    											  R.layout.new_record_item, 
    											  new String[] {"img", "text"}, 
    											  new int[] {R.id.item_img, R.id.item_text});
    	newrecordGridView.setAdapter(adapter);
    }
	
    /**
     * Set listeners to the views.
     */
	private void setOnListeners() {

		viewFlow.setOnViewSwitchListener(new ViewSwitchListener() {

			@Override
			public void onSwitched(View view, int position) {
				mCurrentPage = position;
				if(position == 0) {
					panel.setVisibility(View.VISIBLE);
        			if(!isShow) {
        				panel.setOpen(!panel.isOpen(), true);
    				}
				}  else {
					if(panel.isOpen()) {
						panel.setOpen(false, false);
					}
					panel.setVisibility(View.GONE);
				}
			}
			
		});
		
		newrecordGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				Intent intent;
				switch(position) {
					case 0:
						if(!isShow) {
							panel.setOpen(false, true);
							newNoteLayout.setVisibility(View.VISIBLE);
							showNewRecordAnimation();
							panel.setVisibility(View.GONE);
							isShow = true;
							isEditingNote = true;
						}
						break;
					case 1:
						time = System.currentTimeMillis();
//						File dir = new File(FileUtils.RECORD_PICTURE_DIR); 
//						if(!dir.exists()) {
//							if(!dir.mkdirs()) {
//								return;
//							}
//						}
						//photo storage path
						FileUtil.createDirectory(FileUtil.RECORD_PICTURE_DIR);
						File f = new File(FileUtil.RECORD_PICTURE_DIR, time + ".jpg");
						Uri uriMyImage = Uri.fromFile(f);
						intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, uriMyImage);
						TimeMemory.this.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
						break;
					case 2:
						intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//						intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, sizeLimit);
//						intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, durationLimit);
						startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
						break;
					case 3:
						try {
							intent = new Intent(Intent.ACTION_GET_CONTENT);
							intent.setType("audio/amr");
							intent.setClassName("com.android.soundrecorder", "com.android.soundrecorder.SoundRecorder");
							startActivityForResult(intent, REQUEST_CODE_TAKE_RECORD);
						} catch(Exception e) {
//							intent = new Intent(Media.RECORD_SOUND_ACTION); 
//							startActivityForResult(intent, REQUEST_CODE_TAKE_RECORD); 
							ActivityUtil.showShortTip(mContext, R.string.tip_sound_recorder_failure);
						}
						break;
				}
				
			}
			
		});
		
		search.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onSearchRequested();
			}
			
		});
		
		negative.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				newNoteDisapper();
				isEditingNote = false;
				
				if(!isShow) {
					panel.setOpen(true, true);
				}
			}
			
		});
		
		positive.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if(isEditingNote) {
					String note = newnoteEditText.getText().toString();
					if(null == note || note.equals("")) {
						ActivityUtil.showShortTip(mContext, R.string.tip_content_not_write);
						return;
					}
					
					String category = RecordUtil.getCategory(categoryFamily, categoryLover, categoryFriend);
					if(null == category || category.equals("")) {
						ActivityUtil.showShortTip(mContext, R.string.tip_category_not_selected);
						return;
					}
					
					Record record = new Record();
					record.setCategory(category.toString());
					record.setType(Record.TYPE_TEXT);
					record.setNote(note);
					record.setDate(StringUtil.getCurrnetDate("yyyy.MM.dd HH:mm:ss"));
					
					boolean flag = RecordModel.insertRecord(mContext, record);
					if(flag) {
						ActivityUtil.showShortTip(mContext, R.string.tip_note_add_success);
						updateLists();
					} else {
						ActivityUtil.showShortTip(mContext, R.string.tip_note_add_failure);
					}
					
					newNoteDisapper();
					newnoteEditText.setText("");
					categoryFamily.setChecked(false);
					categoryLover.setChecked(false);
					categoryFriend.setChecked(false);
				}
				
			}
			
		});

		welcomScroll.setOnTouchListener(new OnTouchListener(){
			@Override
			public boolean onTouch(View v, MotionEvent event) {

				return false;
			}
		});
		
		scrollLayout.setOnSnapToEndListener(new OnSnapToEndListener() {

			@Override
			public void onSnapToEnd() {
				img1 = null;
				img2 = null;
				img3 = null;
				img4 = null;
				scrollLayout.setEndSnapStatus(true);
				scrollLayout.removeAllViews();
				scrollLayout.setVisibility(View.GONE);
				guideBg.setVisibility(View.GONE);
				getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
			}
    		
    	});
		
		menuWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				if(panel.getVisibility() == View.VISIBLE) {
					if(!panel.isOpen()) {
						panel.setOpen(true, true);
					}
				}
			}
			
		});
	}
	
	/**
	 * Send message to update list data.
	 */
	private void updateLists(){
		UIHandler.sendEmptyMessage(HANDLER_LISTVIEW);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(resultCode == RESULT_OK) {
			Intent intent;
			String uriPath;
			switch(requestCode) {
				case REQUEST_CODE_TAKE_PHOTO:
					File pictureFile = new File(FileUtil.RECORD_PICTURE_DIR, time + ".jpg");
					if(!pictureFile.exists()) {
						ActivityUtil.showShortTip(mContext, R.string.tip_takephoto_failure);
						return;
					}
					intent = new Intent(mContext, NewPicture.class);
					intent.putExtra("picture", pictureFile.getPath());
					intent.putExtra("picName", time);
					startActivity(intent);
					break;
				case REQUEST_CODE_TAKE_VIDEO:
					uriPath = data.getDataString();
					intent = new Intent(mContext, NewVideo.class);
					intent.putExtra("videoPath", uriPath);
					startActivity(intent);
					break;
					
				case REQUEST_CODE_TAKE_RECORD:
					uriPath = data.getDataString();
					intent = new Intent(mContext, NewSoundRecord.class);
					intent.putExtra("recordPath", uriPath);
					startActivity(intent);
					break;
			}
			
		}
	}

    /******************** Receiver **********************/
    public class UpdateUIReceiver extends BroadcastReceiver {
    	
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(Constants.ACTION_RECORD_ADD)) {
				updateLists();
			}
			
		}
    }
    
    /**
     * Handler used to update UI.
     */
    Handler UIHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {
    		switch(msg.what) {
    		    case HANDLER_LISTVIEW:
    		    	RecordModel.updateDataList(mFamilyData, RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_FAMILY));
					mFamilyAdapter.notifyDataSetChanged();
					RecordModel.updateDataList(mLoverData, RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_LOVER));
					mLoverAdapter.notifyDataSetChanged();
					RecordModel.updateDataList(mFriendData, RecordModel.getRecordListByCategory(mContext, Constants.DATA_TYPE_FRIEND));
					mFriendAdapter.notifyDataSetChanged();
    		        break;
    		    default:
    		    	break;
    		}
    		updateListView();
    		updateDataToCards();
    	}
    };
    
    @Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		 if (menuWindow.isShowing()) {
				menuWindow.dismiss();
				return true;
		 }
		return super.dispatchTouchEvent(ev);
	}
    
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(event.getAction()==KeyEvent.ACTION_DOWN){
			if(event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
				if(panel.isOpen()) {
					panel.setOpen(false, true);
				}
				
				if(!menuWindow.isShowing()) {
					menuWindow.showAtLocation(findViewById(R.id.root_layout), Gravity.BOTTOM, 0, 0);
				} else {
					menuWindow.dismiss();
				}
				return true;
			}
			
			if(event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
				if(menuWindow.isShowing()) {
					menuWindow.dismiss();
					return true;
				}
				
				if(mCurrentPage == 0) {
					if(isEditingNote) {
						ActivityUtil.showShortTip(mContext, R.string.exit_editting_tip);
						return true;
					} else {
						showExitDialog();
					}
				} else {
					showExitDialog();
				}
			}
		}
		return super.dispatchKeyEvent(event);
	}
	
	private void showExitDialog() {
		new AlertDialog.Builder(mContext)
		.setTitle(R.string.exit_title)
		.setPositiveButton(R.string.exit_positive, new Dialog.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				TimeMemory.this.finish();
			}
			
		})
		.setNegativeButton(R.string.exit_negative, null)
		.create()
		.show();
	}
	
	/**
	 * Hide the new note layout.
	 */
	private void newNoteDisapper() {
		newNoteLayout.setVisibility(View.INVISIBLE);
		upBgLayout.setVisibility(View.VISIBLE);
		downBgLayout.setVisibility(View.VISIBLE);
		panel.setVisibility(View.VISIBLE);
		isShow = false;
		isEditingNote = false;
	}
	
	/**
     * show panel animation
     */
    private void showNewRecordAnimation() {
    	upBgLayout.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.newnote_translate_up_out));
		downBgLayout.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.newnote_translate_down_out));
		upBgLayout.setVisibility(View.GONE);
		downBgLayout.setVisibility(View.GONE);
    }
}